<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { isDark } from '@/composables/dark'
import { useUserStore } from '@/stores'
import { setTokenWithTTL, isLogin } from '@/utils/auth'
import { showToast, showSuccessToast } from 'vant'
import { login as userLogin } from '@/api/user'
import { mapRoleFromChinese } from '@/api/user'

import logo from '~/images/logo.svg'
import logoDark from '~/images/logo-dark.svg'
import vw from '@/utils/inline-px-to-vw'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

const dark = ref(isDark.value)

watch(
  () => isDark.value,
  (newMode) => {
    dark.value = newMode
  },
)

const postData = reactive({
  loginName: '',
  password: '',
})

const rules = reactive({
  loginName: [
    { required: true, message: '请输入登录名' },
  ],
  password: [
    { required: true, message: '请输入密码' },
  ],
})

// 模拟用户数据
const mockUsers = [
  {
    username: 'applicant',
    password: '123456',
    userInfo: {
      uid: 1,
      nickname: '申请人',
      avatar: '',
      role: 'applicant'
    },
    token: 'token_applicant_' + Date.now()
  },
  {
    username: 'approver',
    password: '123456',
    userInfo: {
      uid: 2,
      nickname: '审批人',
      avatar: '',
      role: 'approver'
    },
    token: 'token_approver_' + Date.now()
  },
  {
    username: 'warehouse',
    password: '123456',
    userInfo: {
      uid: 3,
      nickname: '仓库管理员',
      avatar: '',
      role: 'warehouse_manager'
    },
    token: 'token_warehouse_' + Date.now()
  }
]

// 检查token是否过期（模拟）
function isTokenExpired(token) {
  if (!token) return true
  
  // 模拟token有效期检查
  const tokenParts = token.split('_')
  if (tokenParts.length < 3) return true
  
  const timestamp = parseInt(tokenParts[2])
  const now = Date.now()
  const expireTime = 24 * 60 * 60 * 1000 // 24小时过期
  
  return (now - timestamp) > expireTime
}

// 检查同一账号是否已在其他地方登录（模拟）
function checkSingleLogin(username, newToken) {
  const existingTokens = localStorage.getItem('user_tokens')
  if (!existingTokens) return true
  
  try {
    const tokens = JSON.parse(existingTokens)
    const userTokens = tokens.filter(item => item.username === username && item.token !== newToken)
    
    if (userTokens.length > 0) {
      const updatedTokens = tokens.filter(item => item.username !== username)
      updatedTokens.push({ username, token: newToken })
      localStorage.setItem('user_tokens', JSON.stringify(updatedTokens))
      
      showToast('检测到该账号在其他设备登录，已将其下线')
      return true
    }
    
    return true
  } catch (error) {
    console.error('Token检查失败:', error)
    return true
  }
}

// 保存用户token记录
function saveUserToken(username, token) {
  const existingTokens = localStorage.getItem('user_tokens')
  let tokens = []
  
  try {
    tokens = existingTokens ? JSON.parse(existingTokens) : []
  } catch (error) {
    tokens = []
  }
  
  tokens = tokens.filter(item => item.username !== username)
  tokens.push({ username, token })
  
  localStorage.setItem('user_tokens', JSON.stringify(tokens))
}

async function login(values) {
  try {
    loading.value = true
    
    // 调用真实登录API
    const response = await userLogin(postData)
    
    if (response.code === 0) {
      const { token, userId, userName, loginName, roles } = response.data
      
      // 映射中文角色到英文
      const mappedRole = mapRoleFromChinese(roles)
      
      // 检查单点登录
      checkSingleLogin(loginName, token)
      
      // 保存token并设置有效期（默认读取 config 的 SESSION_TTL_HOURS）
      setTokenWithTTL(token)
      
      // 构造用户信息
      const userInfo = {
        uid: userId,
        nickname: userName,
        avatar: '',
        role: mappedRole,
        userId,
        userName,
        loginName,
        roles
      }
      
      // 保存用户信息到store
      userStore.userInfo.uid = userInfo.uid
      userStore.userInfo.nickname = userInfo.nickname
      userStore.userInfo.avatar = userInfo.avatar
      userStore.userInfo.role = userInfo.role
      
      // 保存用户token记录
      saveUserToken(loginName, token)
      
      // 保存完整用户信息到localStorage
      localStorage.setItem('user_info', JSON.stringify(userInfo))
      
      showSuccessToast('登录成功')
      
      // 根据角色跳转到outbound页面
      setTimeout(() => {
        router.push({
          name: 'Outbound'
        })
      }, 1000)
    } else {
      showToast(response.msg || '登录失败')
    }
    
  } catch (error) {
    console.error('登录失败:', error)
    showToast(error.message || '登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 页面加载时检查已登录状态（含有效期）
onMounted(() => {
  try {
    if (isLogin()) {
      const userInfo = localStorage.getItem('user_info')
      if (userInfo) {
        const parsedUserInfo = JSON.parse(userInfo)
        userStore.userInfo.uid = parsedUserInfo.uid
        userStore.userInfo.nickname = parsedUserInfo.nickname
        userStore.userInfo.avatar = parsedUserInfo.avatar
        userStore.userInfo.role = parsedUserInfo.role
      }
      router.replace({ name: 'Outbound' })
    }
  } catch (error) {
    // 忽略解析错误，维持在登录页
  }
})
</script>

<template>
  <div class="m-x-a text-center w-7xl">
    <div class="mb-32 mt-20">
      <van-image :src="dark ? logoDark : logo" class="h-120 w-120" alt="brand logo" />
    </div>

    <van-form :model="postData" :rules="rules" validate-trigger="onSubmit" @submit="login">
      <div class="rounded-3xl overflow-hidden">
        <van-field
          v-model="postData.loginName"
          :rules="rules.loginName"
          name="loginName"
          placeholder="请输入登录名"
        />
      </div>

      <div class="mt-16 rounded-3xl overflow-hidden">
        <van-field
          v-model="postData.password"
          type="password"
          :rules="rules.password"
          name="password"
          placeholder="请输入密码"
        />
      </div>

      <div class="mt-16">
        <van-button
          :loading="loading"
          type="primary"
          native-type="submit"
          round block
        >
          登录
        </van-button>
      </div>
    </van-form>

    <!-- 测试账号提示 -->
    <!-- <div class="mt-24 text-xs text-gray-500">
      <div class="mb-8">测试账号：</div>
      <div class="space-y-4">
        <div>出库申请人: shenqingren001 / shenqingren001</div>
      </div>
    </div> -->

    <!-- <GhostButton block to="register" :style="{ 'margin-top': vw(18) }">
      {{ $t('login.signUp') }}
    </GhostButton>

    <GhostButton block to="forgot-password">
      {{ $t('login.forgotPassword') }}
    </GhostButton> -->
  </div>
</template>

<route lang="json5">
{
  name: 'Login'
}
</route>
